"""DataBridge 数据桥接服务

基于FastAPI的数据收集、存储和转发系统
提供会话管理、数据收集、分析等功能的REST API
"""

import os
import sys
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from loguru import logger

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from app.config import settings
from app.core.database import init_database, create_tables
from app.core.database_init import init_database_on_startup
from app.models.brain_wave import BrainWave
from app.models.sleep_monitoring_metrics import SleepMonitoringMetrics
from app.controllers.session_controller import router as session_router
from app.controllers.eeg_controller import router as eeg_router
from app.controllers.analysis_controller import router as analysis_router


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理
    
    启动时初始化数据库，关闭时清理资源
    """
    # 启动时执行
    logger.info("DataBridge 数据桥接服务启动中...")
    
    # 配置日志
    logger.remove()  # 移除默认处理器
    logger.add(
        sys.stdout,
        format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>",
        level=settings.log_level
    )
    
    # 添加文件日志
    if not os.path.exists("logs"):
        os.makedirs("logs")
    
    logger.add(
        "logs/brain_wave_{time:YYYY-MM-DD}.log",
        rotation="1 day",
        retention="30 days",
        format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {name}:{function}:{line} - {message}",
        level=settings.log_level
    )
    
    # 初始化数据库
    try:
        logger.info("开始数据库连接测试和表结构检查...")
        success = init_database_on_startup()
        if success:
            logger.info("数据库初始化成功 - 连接正常，表结构完整")
        else:
            logger.error("数据库初始化失败 - 请检查数据库配置和连接")
            sys.exit(1)
    except Exception as e:
        logger.error(f"数据库初始化异常: {str(e)}")
        logger.error("请检查数据库服务是否启动，配置是否正确")
        sys.exit(1)
    
    logger.info(f"脑波监测系统启动完成，运行在 {settings.app_host}:{settings.app_port}")
    
    yield
    
    # 关闭时执行
    logger.info("脑波监测系统正在关闭...")


# 创建FastAPI应用实例
app = FastAPI(
    title="脑波监测系统",
    description="基于FastAPI的脑波数据收集和分析系统",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.allowed_origins,
    allow_credentials=True,
    allow_methods=settings.allowed_methods,
    allow_headers=settings.allowed_headers,
)

# 注册路由
app.include_router(session_router, prefix=settings.api_prefix)
app.include_router(eeg_router, prefix=settings.api_prefix)
app.include_router(analysis_router, prefix=settings.api_prefix)


@app.get("/", summary="系统状态")
async def root():
    """系统根路径，返回系统状态信息"""
    return {
        "message": "DataBridge 数据桥接服务运行正常",
        "version": "1.0.0",
        "status": "running",
        "docs": "/docs"
    }


@app.get("/health", summary="健康检查")
async def health_check():
    """健康检查接口"""
    return {
        "status": "healthy",
        "timestamp": "2024-01-15T12:00:00Z"
    }


if __name__ == "__main__":
    import uvicorn
    
    # 运行应用
    uvicorn.run(
        "main:app",
        host=settings.app_host,
        port=settings.app_port,
        reload=settings.debug,
        log_level=settings.log_level.lower(),
        access_log=True  # 启用访问日志
    )